package com.roger.homecenterscreen.voice

import android.util.Log
import com.roger.homecenterscreen.config.BusinessConfig
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject
import java.io.File
import java.util.concurrent.TimeUnit

data class VoiceprintUser(
    val userId: String?,
    val userName: String?,
    val extra: JSONObject?
)

/**
 * 声纹识别服务调用
 * 将录到的音频文件POST到接口进行识别，解析并返回用户信息
 */
class VoiceprintService {
    private val TAG = "VoiceprintService"
    private val client = OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(20, TimeUnit.SECONDS)
        .writeTimeout(20, TimeUnit.SECONDS)
        .build()

    /**
     * 调用声纹识别接口
     * @param wavFile 需要识别的WAV文件（PCM 16bit 单声道）
     */
    fun verify(wavFile: File): VoiceprintUser? {
        return try {
            val baseUrl = BusinessConfig.serverHttpBaseUrl.trimEnd('/')
            val path = BusinessConfig.voiceprintVerifyPath
            val url = "$baseUrl$path"

            val audioRequestBody: RequestBody = wavFile.asRequestBody("audio/wav".toMediaType())
            val multipartBody = MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("audioFile", wavFile.name, audioRequestBody)
                .build()

            val reqBuilder = Request.Builder()
                .url(url)
                .post(multipartBody)
                .addHeader("Accept", "application/json")
            // 如接口需要鉴权：请在 BusinessConfig 中新增专用 voiceprintAuthToken，并在此添加
            // 当前不复用 CosyVoice 鉴权字段，避免误用 TTS 密钥

            val resp = client.newCall(reqBuilder.build()).execute()
            if (!resp.isSuccessful) {
                Log.w(TAG, "verify http ${resp.code}")
                return null
            }
            val bodyStr = resp.body?.string() ?: return null
            val json = JSONObject(bodyStr)

            // 尝试解析常见格式（根据 voiceprint01.json 实际字段调整）
            val success = json.optBoolean("success", true)
            if (!success) return null

            val data = json.optJSONObject("data") ?: json
            val userId = data.optString("userID", null)
            val userName = data.optString("nickName", null)
            Log.d(TAG, "verify result -> userId:$userId, userName:$userName")
            return VoiceprintUser(userId = userId, userName = userName, extra = data)
        } catch (e: Exception) {
            Log.e(TAG, "voiceprint verify error", e)
            null
        }
    }
}